import React, {Component} from 'react';
import {
    Image,
    StyleSheet,
    Text,
    View,
    TextInput,
    TouchableOpacity,
    DrawerLayoutAndroid,
    StatusBar, FlatList, SectionList,
} from 'react-native';
// import {fetch} from "react-native/Libraries/react-native/react-native-interface";

import DataUtil from '../../util/DataUtil'
import CitySectionList from '../../comps/normal/mySideBar'


let url='https://edu.bjzjmy.com:4455/register/cities?cityId=1';
let sectionsList;
let baseData;
const ITEM_HEIGHT = 40; //item的高度
const HEADER_HEIGHT = 30;  //分组头部的高度
const SEPARATOR_HEIGHT = 0; //分割线的高度

export default class Resource extends React.Component {

    constructor(){
        super();
        this.state={
            loading:'false',
            firstAll:[],
            data:''
        }
    }

    //组件挂载完成开始加载数据
    componentDidMount() {


    }

    render() {
        if (this.state.loading==='false'){
            this.getData();
            return(
                <View style={styles.container}>
                    <Text>loading............</Text>
                </View>
            )
        }else {
            // let a3=[{title:'A',data:[{name:'安徽',id:3}],key:0},{title:'B',data:[{name:'北京',id:2}],key:1},{title:'C',data:[{name:'重庆',id:32}],key:2},{title:'F',data:[{name:'福建',id:4}],key:3},{title:'G',data:[{name:'甘肃',id:5},{name:'广东',id:6},{name:'广西',id:7},{name:'贵州',id:8}],key:4},{title:'H',data:[{name:'海南',id:9},{name:'河北',id:10},{name:'河南',id:11},{name:'黑龙江',id:12},{name:'湖北',id:13},{name:'湖南',id:14}],key:5},{title:'J',data:[{name:'吉林',id:15},{name:'江苏',id:16},{name:'江西',id:17}],key:6},{title:'L',data:[{name:'辽宁',id:18}],key:7},{title:'N',data:[{name:'内蒙古',id:19},{name:'宁夏',id:20}],key:8},{title:'Q',data:[{name:'青海',id:21}],key:9},{title:'S',data:[{name:'山东',id:22},{name:'山西',id:23},{name:'陕西',id:24},{name:'上海',id:25},{name:'四川',id:26}],key:10},{title:'T',data:[{name:'天津',id:27}],key:11},{title:'X',data:[{name:'西藏',id:28},{name:'新疆',id:29}],key:12},{title:'Y',data:[{name:'云南',id:30}],key:13},{title:'Z',data:[{name:'浙江',id:31}],key:14},];
            return (
                <View style={{flex:1}}>
                    <View style={styles.navGroup}>
                        <TouchableOpacity style={styles.scenes}>
                            <Text style={[styles.title,{marginLeft:5,fontSize:13}]}>&lt; 返回</Text>
                        </TouchableOpacity>
                        <View style={[styles.scenes,{alignItems:'center'}]}>
                            <Text style={[styles.title,{fontSize:16}]}>初始化密码</Text>
                        </View>
                        <View style={styles.scenes}></View>
                    </View>
                    <View>
                    <SectionList
                        style={{marginBottom:45}}
                        ref='list'
                        enableEmptySections
                        sections={this._solveData(this.state.data)}
                        // renderItem={({item}) => <Text style={styles.name}>{item.name}</Text>}
                        // renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
                        renderItem={({item})=>
                            <View style={styles.itemView}>
                                <Text style={{marginLeft: 5, fontSize: 16, color: '#333'}}>
                                    {item.name}
                                </Text>
                            </View>}
                        renderSectionHeader={({section})=>
                            <View style={[styles.headerView,{justifyContent:'center',backgroundColor:"#eceeef"}]}>
                                <Text style={styles.headerText}>{section.title}</Text>
                            </View>
                        }
                        ItemSeparatorComponent={()=><View style={{height:1,width:500,backgroundColor:'#F8FAFB'}}></View>}
                        getItemLayout={this._getItemLayout}
                    />
                        <CitySectionList
                            sections={ this.getFirstAll(this.state.data)}
                            onSectionSelect={this._onSectionselect}
                        />

                    </View>
                </View>
            );
        }
    }

    /**
     * 请求数据
     */
    getData() {
        fetch(url)
            .then((response)=>{
                return response.json()
            })
            .then((responseData)=>{
                //得到数据,刷新组建
                // setData(responseData);
                this.setState({
                    loading:'true',
                    data:responseData
                });
                baseData=responseData
            })
            .catch((error)=>{
                console.error(error);
            });
    }

    /**
     * 吧json数据转化为sections数据
     * @param responseData
     *
       [
     {title: 'D', data: [{name:'Devin',id=0}]},
     {title: 'J', data: [{name:'Jackson',id=0},{name:'James',id=0}] },
   ]
     *
     */
    setData(responseData) {
        let jsonData=responseData.list;
        let data='[';
        let firstAll=[];
        let item_end='],';
        // 遍历字母
        // console.log(JSON.stringify(responseData));
        // console.log(responseData);

        for(let i=0;i<jsonData.length;i++){
            let first=jsonData[i].first;
            if(!DataUtil.contains(firstAll,first)){
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length]=first;
            }
        }
        firstAll.sort();

        //字母数组已排序 , 开始按照字母顺序拼接
        for (let j=0;j<firstAll.length;j++){
            //预定义title
            let item='{"title":"'+firstAll[j]+'","data":[';
            for(let z=0;z<jsonData.length;z++){
                if (firstAll[j]==jsonData[z].first){
                    item=item+'{"name":"'+jsonData[z].name+'","id":"+jsonData[z].id+"},';
                }
            }
            item=item.substr(0,item.length-1);
            item+='],';
            item+='"key":'+j+'},';
            // console.log(item);
            data+=item
        }
        data+=']';
        return data;
    }

    /**
     * 吧json数据转化为sections的对象数据
     * @param responseData
     *
     [
     {title: 'D', data: [{name:'Devin',id=0}]},
     {title: 'J', data: [{name:'Jackson',id=0},{name:'James',id=0}] },
     ]
     *
     */
    _solveData(responseData){
        console.log(JSON.stringify(responseData));
        let jsonData=responseData.list; //JSON数据
        let finalData=[]; //最终数组对象
        let firstAll=[]; //首字母集合

        //首先封装出现过的首字母
        for(let i=0;i<jsonData.length;i++){
            let first=jsonData[i].first;
            if(!DataUtil.contains(firstAll,first)){
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length]=first;
            }
        }
        firstAll.sort();


        //根据首字母进行对象的封装
        for (let j=0;j<firstAll.length;j++){
            let item={}; //定义单个条目
            item.title=firstAll[j]; //条目的标题

            let item_obj=[];//条目中data的数组
            for(let z=0;z<jsonData.length;z++){
                if (firstAll[j]==jsonData[z].first){
                    let inner={}
                    inner.name = jsonData[z].name;
                    inner.key = jsonData[z].id;
                    item_obj[item_obj.length]=inner;
                }
            }
            item.data=item_obj; //条目数据
            item.keys=j;  //条目key
            finalData[j]=item
        }
        console.log(finalData);
        return finalData;
    }

    _onSectionselect = (section, index) => {
        //跳转到某一项
        // this.refs.list.scrollToIndex({animated: true, index: this.state.sectionSize[index]})
        this.refs.list.scrollToLocation({animated : true,
            sectionIndex: index-1,
            itemIndex : 0,
            viewPosition: 0,
            viewOffset : 0});

        console.log(index);
        console.log(section)
    };

    getFirstAll(data) {
        //首先封装出现过的首字母
        let firstAll=[];
        let jsonData=data.list;
        for(let i=0;i<jsonData.length;i++){
            let first=jsonData[i].first;
            if(!DataUtil.contains(firstAll,first)){
                //第一次出现的字母, 添加到集合中并生成新的item项
                firstAll[firstAll.length]=first;
            }
        }
        firstAll.sort();
        return firstAll;
    }

    _getItemLayout(data, index) {
        let [length, separator, header] = [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER_HEIGHT];
        return {length, offset: (length + separator) * index + header, index};
    };
}

class resource extends Component{
    render(){
        return(
            <View>
                <Text>资源</Text>
            </View>
        )
    }
}

const styles=StyleSheet.create({
    container:{
        flex:1,
        justifyContent:'center',
        alignItems:'center',
    },
    sectionHeader: {
        paddingTop: 2,
        paddingLeft: 10,
        paddingRight: 10,
        paddingBottom: 2,
        fontSize: 14,
        fontWeight: 'bold',
        backgroundColor: 'rgba(247,247,247,1.0)',
    },
    item: {
        padding: 10,
        fontSize: 18,
        height: 44,
    },
    headerView: {
        justifyContent: 'center',
        height: HEADER_HEIGHT,
        paddingLeft: 20,
        backgroundColor: '#eee'
    },
    headerText: {
        fontSize: 15,
        // fontWeight: 'bold',
        // color: '#3cb775'
    },
    itemView: {
        justifyContent:'center',
        backgroundColor:"#fff",
        flexDirection: 'column',
        padding: 12,
        alignItems: 'flex-start',
        height: ITEM_HEIGHT
    },
    navGroup: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
        height: 50,
        paddingHorizontal: 5
    },
    scenes: {
        flex: 1
    },
});

